﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using TemplateFoundation.Exceptions;

namespace TemplateFoundation.Handlers
{
    /// <summary>
    /// Provides access to images embedded in the EPiServer Template Foundation assembly
    /// </summary>
    public class EmbeddedImagesHandler : IHttpHandler
    {
        #region IHttpHandler Members

        private byte[] _image;
        private const string REQUEST_URL_PREFIX = "/TemplateFoundation/Images/";

        /// <summary>
        /// 
        /// </summary>
        public EmbeddedImagesHandler()
        {
            var url = HttpContext.Current.Request.Url.AbsolutePath;

            if (!url.StartsWith(REQUEST_URL_PREFIX,StringComparison.OrdinalIgnoreCase))
            {
                throw new TemplateFoundationException("Requests for image loader must be for a relative path starting with '" + REQUEST_URL_PREFIX + "'");
            }

            url = url.Substring(REQUEST_URL_PREFIX.Length).Replace('/', '.');

            var file = GetType().Assembly.GetManifestResourceStream("TemplateFoundation.Images." + url);
            if (file==null)
            {
                throw new TemplateFoundationException("Requested embedded image could not be found");
            }

            var image = Image.FromStream(file);

            var stream = new MemoryStream();

            image.Save(stream, ImageFormat.Png);

            _image = stream.ToArray();

            // Clean up
            stream.Close();
            stream.Dispose();
            image.Dispose();
        }

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        /// </returns>
        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            // TODO Send correct MIME type based on file extension

            context.Response.ContentType = "image/png";
            context.Response.BinaryWrite(_image);
            context.Response.End();
        }

        #endregion
    }
}
